package com.wang.springbootinit.component;

import cn.hutool.core.util.StrUtil;
import com.wang.springbootinit.model.vo.LoginUserVO;
import com.wang.springbootinit.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class TokenComponent {
    private static final Long MILLIS_MINUTE = 60 * 1000L;
    private static final int expireTime = 5 * 60; // 令牌有效期（默认30分钟）
    private static final String TOKEN_REDIS = "TOKEN:USER:";
    public static final String HEADER_AUTHORIZATION_KEY = "Authori-zation";

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUserVO getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StrUtil.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            return redisUtil.get(userKey);
        }
        return null;
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token,HttpServletRequest request) {
        if (StrUtil.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            redisUtil.delete(userKey);
        }else{
            String currentToken = getToken(request);
            if (StrUtil.isNotEmpty(currentToken)) {
                redisUtil.delete(currentToken);
            }
        }
    }


    public String createToken(LoginUserVO loginUser) {
        String token = UUID.randomUUID().toString().replace("-", "");
        loginUser.setToken(token);
        refreshToken(loginUser);
        return token;
    }


    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUserVO loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisUtil.set(userKey, loginUser, (long) expireTime, TimeUnit.MINUTES);
    }

    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(HEADER_AUTHORIZATION_KEY);
        if (StrUtil.isNotEmpty(token) && token.startsWith(TOKEN_REDIS)) {
            token = token.replace(TOKEN_REDIS, "");
        }
        return token;
    }

    private String getTokenKey(String uuid) {
        return TOKEN_REDIS + uuid;
    }
}
